/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.ui.chat.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import org.jb.notification.client.Notification;
import org.jb.notification.server.NotificationManager;
import org.jb.notification.server.NotificationProvider;
import org.jb.room.server.RoomScoped;
import org.jb.ui.chat.client.ChatMessage;
import org.jb.ui.chat.client.rpc.ChatService;
import org.jb.user.client.UserLogin;
import org.jb.user.server.LoginRequired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Provider;

/**
 * 
 * @author jeremie
 *
 */
@RoomScoped
public class ChatServiceImpl implements ChatService, NotificationProvider {

	private final static Logger logger = LoggerFactory.getLogger(ChatServiceImpl.class);

	@Inject @UserLogin
	private Provider<String> userProvider;
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.coinche.server.notify.NotificationProvider#notify(java.util.Collection, java.util.Date)
	 */
	@Override
	synchronized public void notify(Collection<Notification> notifications, long fromCheckpoint, long toCheckpoint ) {
		for( ChatMessage msg : messages ) {
			if (fromCheckpoint < msg.getCheckpoint() && msg.getCheckpoint() <= toCheckpoint)
				notifications.add( msg );
		}
	}
	
	public void setUserProvider( Provider<String> userProvider ) {
		this.userProvider = userProvider;
	}
	
	@Inject
	public void setRoomNotificationManager( NotificationManager notificationManager ) {
		this.notificationManager = notificationManager;
	}

	/*
	 * (non-Javadoc)
	 * @see org.jb.coinche.client.chat.ChatService#sendMessage(org.jb.coinche.client.chat.ChatMessage)
	 */
	@LoginRequired
	 synchronized public void sendMessage(String message) {
		
		 logger.debug("Received new chatmessage {}", message );
			
		 ChatMessage msg = new ChatMessage();
		 msg.setMessage( message.replaceAll("<", "&#60;") );
		 msg.setDate( new Date() );
		 msg.setUser( userProvider.get() );
		 messages.add( msg );
		
		 if (notificationManager != null) 
			msg.setCheckpoint( notificationManager.getNextId() );	
		 
		 notificationManager.wakeup();
	}
	
	private ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>();
	private NotificationManager notificationManager;

}
